package com.example.bookappgraduation;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;

import com.example.bookappgraduation.adapters.BookAdapter;
import com.example.bookappgraduation.models.Book;
import com.example.bookappgraduation.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class BookListActivity extends AppCompatActivity {

    private RecyclerView recyclerViewBooks;
    private BookAdapter bookAdapter;
    private List<Book> bookList;
    private ProgressBar progressBar;
    private String categoryId;
    private String searchQuery;
    private String categoryName; // 用于设置标题
    private final String API_KEY = "b55327fd83f2024e30500e63448a565d"; // 直接使用或从strings.xml获取

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);

        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        recyclerViewBooks = findViewById(R.id.recyclerViewBooks);
        progressBar = findViewById(R.id.progressBarBookList);
        recyclerViewBooks.setLayoutManager(new LinearLayoutManager(this));
        bookList = new ArrayList<>();
        bookAdapter = new BookAdapter(this, bookList);
        recyclerViewBooks.setAdapter(bookAdapter);

        categoryId = getIntent().getStringExtra("category_id");
        searchQuery = getIntent().getStringExtra("search_query");
        categoryName = getIntent().getStringExtra("category_name"); // 获取分类名称

        if (categoryName != null && getSupportActionBar() != null) {
            getSupportActionBar().setTitle(categoryName); // 设置Activity标题为分类名称
        } else if (searchQuery != null && getSupportActionBar() != null) {
            getSupportActionBar().setTitle("搜索结果: " + searchQuery);
        }

        fetchBooks();
    }

    private void fetchBooks() {
        progressBar.setVisibility(View.VISIBLE);
        String baseUrl = "http://apis.juhe.cn/goodbook/query";

        // 使用 Uri.Builder 来安全地构建 URL，比手动拼接字符串更健壮
        Uri.Builder builder = Uri.parse(baseUrl).buildUpon();
        builder.appendQueryParameter("key", API_KEY);
        builder.appendQueryParameter("rn", "30");

        String url;

        if (categoryId != null && !categoryId.isEmpty()) {
            builder.appendQueryParameter("catalog_id", categoryId);
            url = builder.build().toString();
        } else if (searchQuery != null && !searchQuery.isEmpty()) {
            try {
                String encodedQuery = URLEncoder.encode(searchQuery, "UTF-8");
                builder.appendQueryParameter("q", encodedQuery);
                builder.appendQueryParameter("catalog_id", "252");
                url = builder.build().toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Toast.makeText(this, "搜索词编码失败", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
                return; // 编码失败，终止网络请求
            }
        } else {
            // 如果两个参数都为空，说明逻辑有问题，我们不再发起错误的请求
            // 而是直接提示用户并结束，这能防止看到来自服务器的错误。
            Toast.makeText(this, "错误：没有提供有效的分类或搜索词", Toast.LENGTH_LONG).show();
            progressBar.setVisibility(View.GONE);
            // finish(); // 你可以选择直接关闭这个页面
            return;
        }

        // 在 Logcat 中打印最终将要请求的 URL，方便检查
        //Log.d("BookListActivity", "Requesting URL: " + url);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                response -> {
                    progressBar.setVisibility(View.GONE);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("error_code") == 0) {
                            JSONObject resultObject = jsonObject.getJSONObject("result");
                            JSONArray dataArray = resultObject.getJSONArray("data");
                            bookList.clear();
                            for (int i = 0; i < dataArray.length(); i++) {
                                JSONObject bookObject = dataArray.getJSONObject(i);
                                Book book = new Book(
                                        bookObject.optString("title"),
                                        bookObject.optString("sub1"),
                                        bookObject.optString("sub2"),
                                        bookObject.optString("img"),
                                        bookObject.optString("catalog"),
                                        bookObject.optString("reading"),
                                        bookObject.optString("online"),
                                        bookObject.optString("bytime")
                                );
                                if (categoryId != null) book.setCatalog_id(categoryId);
                                bookList.add(book);
                            }
                            bookAdapter.notifyDataSetChanged();
                            if(bookList.isEmpty()){
                                Toast.makeText(BookListActivity.this, "没有找到相关书籍", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(BookListActivity.this, "获取书籍失败: " + jsonObject.getString("reason"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(BookListActivity.this, "JSON 解析错误", Toast.LENGTH_SHORT).show();
                    }
                },
                error -> {
                    progressBar.setVisibility(View.GONE);
                    Log.e("BookListActivity", "Volley Error: " + error.toString());
                    Toast.makeText(BookListActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                });

        VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
    }

    // 处理返回按钮点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 关闭当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}